package com.cq.hd.app.controller;

import com.cq.hd.common.annotation.LoginUser;
import com.cq.hd.common.entity.AppLoginUser;
import com.cq.hd.common.entity.BusinessInfo;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Result;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.product.api.TbGoodsApi;
import com.cq.hd.product.api.dto.GoodsActivePageDto;
import com.cq.hd.product.api.vo.GoodsActivePageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

@RestController
@RequestMapping("/goods")
@Api(tags = "商品相关接口")
public class GoodsController {

    @Autowired
    private TbGoodsApi goodsApi;

    @Autowired
    private TbBusinessApi businessApi;

    @ApiOperation(value = "创建活动选择商品列表")
    @ApiImplicitParam(name = "goodsActivePageDto", value = "实体", paramType = "query", dataType = "GoodsActivePageDto")
    @ApiResponse(response = GoodsActivePageVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/pageGoodsActive")
    public Result<Page<GoodsActivePageVo>> pageGoodsActive(GoodsActivePageDto goodsActivePageDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        Long merchantId = goodsActivePageDto.getMerchantId();
        // 如果没选择商户，查询该商家下的所有有效商户的商品
        if (merchantId == null || merchantId == 0) {
            Long businessId = null;
            BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
            if (businessInfo != null) {
                businessId = businessInfo.getId();
            }

            // 需要查找该商家下的所有有效的商户id
            List<Long> merchantIds = businessApi.listRelationMerchantId(appLoginUser.getUserId(), businessId).unpack();
            if (!CollectionUtils.isEmpty(merchantIds)) {
                goodsActivePageDto.setMerchantIds(merchantIds);
            }
        }

        return goodsApi.pageGoodsActive(goodsActivePageDto);
    }

}
